# -*- coding: utf-8 -*-
# @Time : 2023/11/29 11:31:46
# @Author : sacon
# @File : register.py
import random
import string
import time

from faker import Faker
# 生成随机姓名
fake = Faker(locale='zh_CN')



# -*- coding: utf-8 -*-
from Api.Request2_new import Request2
import os
import uuid

import requests
from Api.BookAccountNumberManage.ocr import ocr_img
from Api.BookAccountNumberManage.retry_model import MyRetry
from Config.config import IMAGE_DIR, logger
from Api.BookAccountNumberManage.get_proxy import get_proxy


from Api.BookAccountNumberManage.redis_client import redis_client
redis_client = redis_client.redis_pool

# from Api.BookAccountNumberManage.phone import phone_obj
from Api.BookAccountNumberManage.phone_taxin import phone_taxin_obj




class RefreshCookie:
    def __init__(self):
        self.cookie = {}
        self.head = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'
        }
        os.makedirs(IMAGE_DIR) if not os.path.isdir(IMAGE_DIR) else ''

    @MyRetry(times=5, return_obj=False)
    def download_and_ocr_img(self):
        try:
            # res = requests.get('http://www.ucdrs.superlib.net/user/vImage.jsp', headers=self.head, cookies=self.cookie, timeout=15, proxies=get_proxy())
            res = Request2.send_request('http://www.ucdrs.superlib.net/user/vImage.jsp', headers=self.head,cookies=self.cookie, timeout=15)
            code_path = os.path.join(IMAGE_DIR, f'{uuid.uuid4()}.jpg')
            with open(code_path, 'wb') as f:
                f.write(res.content)
            code = ocr_img(code_path)
            if code:
                return code
            else:
                raise ValueError('ocr失败')
        except Exception as e:
            raise ValueError(e)
        finally:
            if os.path.isfile(code_path):
                os.remove(code_path)


    @MyRetry(times=5, return_obj=False)
    def try_register(self, username, password, code,tel_code,phone,name):
        headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded",
            "Origin": "http://user.superlib.net",
            "Pragma": "no-cache",
            "Referer": "http://user.superlib.net/user/register.action?time=20231129113027&sn=BE8325EE625A25AF0514BD530EF92158",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
        }
        url = "http://user.superlib.net/user/addone"
        data = {
            "username": username,
            "password": password,
            "pswd2": password,
            "email": f"{''.join([str(random.choice(range(1,10))) for _ in range(9)])}@qq.com",
            "displayname": name,
            "unitId": "7320",
            "checkcode": code,
            "tel": phone,
            "telcode": tel_code,
            "subUnitInfo": ""
        }
        # res = requests.post(url, headers=headers, cookies=self.cookie, data=data, verify=False)
        res = Request2.send_request(url, method='post', headers=headers, cookies=self.cookie, data=data, verify=False, timeout=20)
        if res.status_code == 200 and '注册成功' in res.text:
            logger.info(f'用户: {username} 注册成功')
            return True
        else:
            raise ValueError(f'注册失败，状态码: {res.status_code}')


    def phone_send_code(self,phone,code):
        headers = {
            "Accept": "*/*",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Pragma": "no-cache",
            "Referer": "http://user.superlib.net/user/register.action?time=20231129113027&sn=BE8325EE625A25AF0514BD530EF92158",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0",
            "X-Requested-With": "XMLHttpRequest"
        }
        url = "http://user.superlib.net/user/sendcode.action"
        params = {
            "tel": phone,
            "checkcode": code,
            "_": str(int(time.time()*1000))
        }
        # response = requests.get(url, headers=headers, cookies=self.cookie, params=params, verify=False)
        response = Request2.send_request(url, headers=headers, cookies=self.cookie, params=params, verify=False, timeout=20)
        if response.text == '发送成功':
            return True
        else:
            logger.error(f'发送验证码失败，状态码: {response.status_code}, 响应: {response.text}')
            return False


    @MyRetry(times=5, return_obj=(False,False,False))
    def register(self):
        logger.info(f'开始注册用户')
        login_url = 'http://www.ucdrs.superlib.net/login/login.action'
        head = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Host': 'www.ucdrs.superlib.net',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
            'Pragma': 'no-cache',
            'Proxy-Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1'
        }
        # res = requests.get(login_url, headers=head, proxies=get_proxy(), timeout=20)
        res = Request2.send_request(login_url, headers=head, timeout=20)
        self.cookie = {i[0]: i[1] for i in res.cookies.items()}
        times = 0
        while True:
            if times == 10:
                logger.warning(f'尝试10次未注册成功')
                return False
            else:
                times += 1
            code = self.download_and_ocr_img()
            if not code:
                # raise ValueError('ocr验证码失败')
                logger.error('ocr验证码失败,重新获取')
                continue

            #todo 通过验证接码平台获取手机号
            phone = phone_taxin_obj.get_phone()
            if not phone:
                logger.error('获取手机号失败,重新获取')
                continue
            logger.debug(f'获取到手机号: {phone}')

            # 基于验证码发送短信
            send_result = self.phone_send_code(phone, code)
            if not send_result:
                logger.error('发送短信失败,重新获取')
                continue
            logger.debug(f'发送短信成功,手机号: {phone}')

            #todo 通过接口获取接码平台的验证码
            tel_code = phone_taxin_obj.get_phone_code(phone)
            if not tel_code:
                logger.error('获取短信验证码失败,重新获取')
                continue

            logger.debug(f'获取到短信验证码: {tel_code}')


            # 基于手机号生成账号，格式为 两个字母+手机号
            username = f'{random.choice(string.ascii_letters)}{random.choice(string.ascii_letters)}{phone}'
            #  生成密码，为 两位大写字母开头+2-3位大小写字母+4到6位数字
            password = f'{random.choice(string.ascii_uppercase)}{random.choice(string.ascii_uppercase)}{random.choice(string.ascii_letters)}{random.choice(string.ascii_uppercase)}{random.choice(string.ascii_uppercase)}{random.choice(string.ascii_letters)}{random.choice(string.ascii_letters)}{random.choice(string.digits)}{random.choice(string.digits)}{random.choice(string.digits)}{random.choice(string.digits)}{random.choice(string.digits)}{random.choice(string.digits)}{random.choice(["#","%","&"])}'
            logger.info(f'生成账号: {username} 密码: {password}')
            # 注册
            try_res = self.try_register(username, password, code,tel_code,phone,fake.name())
            if not try_res:
                continue

            phone_taxin_obj.release_phone(phone)

            #todo 将账号入库

            return username,password,phone


refresh = RefreshCookie()
if __name__ == '__main__':
    refresh.register()











